<template>
  <el-form>
    <el-form-item label="SPU名称">
      <el-input placeholder="SPU名称" v-model="spuForm.spuName"></el-input>
    </el-form-item>
    <el-form-item label="品牌">
      <el-select placeholder="请选择" v-model="spuForm.tmId">
        <el-option
          :value="(tm.id as number)"
          :label="tm.tmName"
          v-for="(tm, index) in trademarkList"
          :key="tm.id"
        ></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="SPU描述">
      <el-input
        placeholder="SPU描述"
        type="textarea"
        rows="4"
        v-model="spuForm.description"
      ></el-input>
    </el-form-item>

    <el-form-item label="SPU图片">
      <el-upload
        v-model:file-list="(spuImageList as any)"
        action="/app-dev/admin/product/fileUpload"
        list-type="picture-card"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove"
        :on-success="handleSuccess"
      >
        <el-icon><Plus /></el-icon>
      </el-upload>

      <el-dialog v-model="dialogVisible">
        <img w-full :src="dialogImageUrl" alt="Preview Image" />
      </el-dialog>
    </el-form-item>

    <el-form-item label="销售属性">
      <el-select
        :placeholder="
          unUsedSaleAttrList.length
            ? `还有${unUsedSaleAttrList.length}未选择`
            : '没有啦！！！'
        "
        v-model="saleAttrIdName"
      >
        <el-option
          v-for="unUsedSaleAttr in unUsedSaleAttrList"
          :value="`${unUsedSaleAttr.id}:${unUsedSaleAttr.name}`"
          :label="unUsedSaleAttr.name"
          :key="unUsedSaleAttr.id"
        ></el-option>
      </el-select>
      <el-button type="primary" @click="addSaleAttr" :disabled="!saleAttrIdName"
        >添加</el-button
      >
    </el-form-item>
    <el-form-item label=""></el-form-item>
    <el-form-item>
      <el-table :data="spuSaleAttrList" border stripe>
        <el-table-column
          type="index"
          label="序号"
          align="center"
          width="80"
        ></el-table-column>
        <el-table-column label="属性名" prop="saleAttrName"></el-table-column>
        <el-table-column label="属性值名称列表">
          <template v-slot="{ row, $index }">
            <el-tag
              v-for="(spuSaleAttr, index) in row.spuSaleAttrValueList"
              :key="spuSaleAttr.id"
              class="mx-1"
              closable
              :disable-transitions="false"
              @close="row.spuSaleAttrValueList.splice(index, 1)"
            >
              {{ spuSaleAttr.saleAttrValueName }}
            </el-tag>
            <el-input
              v-if="row.isEdit"
              ref="InputRef"
              v-model="row.saleAttrValueName"
              class="ml-1 w-20"
              size="small"
              @keyup.enter="$event.target.blur()"
              @blur="handleInputConfirm(row)"
            />
            <el-button
              v-else
              class="button-new-tag ml-1"
              size="small"
              @click="showInput(row)"
            >
              添加
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="{ row, $index }">
            <el-button
              type="danger"
              size="small"
              icon="ele-Delete"
              title="删除销售属性"
              @click="spuSaleAttrList.splice($index, 1)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item>
      <template v-slot="{ row, $index }">
        <el-button
          type="primary"
          @click="save"
          :disabled="!spuSaleAttrList.length"
          >保存</el-button
        >
        <el-button type="default" @click="showUpdateSpuFrom">取消</el-button>
      </template>
    </el-form-item>
  </el-form>
</template>
<script lang="ts">
import { defineComponent } from "vue";
export default defineComponent({
  name: "SpuForm",
});
</script>
<script lang="ts" setup>
import { ref, onMounted, nextTick, computed } from "vue";
import { useCategoryStore } from "@/stores/category";
import { Plus } from "@element-plus/icons-vue";

import {
  ElMessage,
  ElInput,
  type UploadProps,
  type UploadUserFile,
} from "element-plus";
import type {
  SpuData,
  BaseSaleAttrData,
  SpuImageData,
  SpuSaleAttrData,
  ResponseData,
} from "@/api/spu";
import { cloneDeep } from "lodash";
import spuApi from "@/api/spu";
import skuApi from "@/api/sku";
import trademarkApi, { type TrademarkData } from "@/api/trademark";

const props = defineProps<{
  spu: SpuData;
}>();

// 把收到的row深拷贝一份
const spuForm = ref(cloneDeep(props.spu));

// 发请求获取初始化的动态数据
const baseSaleAttrList = ref<BaseSaleAttrData[]>([]); // 所有的销售属性列表
const trademarkList = ref<TrademarkData[]>([]);
const spuImageList = ref<SpuImageData[]>([]);
const spuSaleAttrList = ref<SpuSaleAttrData[]>([]); // 自己的销售属性列表

const getInitAddSpuFormData = async () => {
  // 获取所有的基础销售属性列表
  const promise1 = spuApi.getBaseSaleAttrList();
  // 获品牌列表
  const promise2 = trademarkApi.getList();
  try {
    const result = await Promise.all([promise1, promise2]);
    baseSaleAttrList.value = result[0];
    trademarkList.value = result[1];
  } catch (error) {
    ElMessage.error("获取初始化数据失败");
  }
};

const getInitUpdateSpuFormData = async () => {
  // 获取所有的基础销售属性列表
  const promise1 = spuApi.getBaseSaleAttrList();
  // 获品牌列表
  const promise2 = trademarkApi.getList();
  // 根据spuid获取商品图片列表
  const promise3 = skuApi.getSpuImageList(spuForm.value.id as number);
  // 根据spuid获取商品自己的销售属性列表
  const promise4 = skuApi.getSpuSaleAttrList(spuForm.value.id as number);
  try {
    const result = await Promise.all([promise1, promise2, promise3, promise4]);
    baseSaleAttrList.value = result[0];
    trademarkList.value = result[1];
    // 遍历spuImageList添加 name 和 url
    let imgList = result[2];
    imgList.forEach((item) => {
      item.name = item.imgName;
      item.url = item.imgUrl;
    });
    spuImageList.value = imgList;
    spuSaleAttrList.value = result[3];
  } catch (error) {
    ElMessage.error("获取初始化数据失败");
  }
};

// 取消spu
const emits = defineEmits(["changeState"]);
const showUpdateSpuFrom = () => {
  emits("changeState", 1);
};

onMounted(() => {
  if (spuForm.value.id) {
    getInitUpdateSpuFormData();
  } else {
    getInitAddSpuFormData();
  }
});
// 计算销售属性下拉框列表
const unUsedSaleAttrList = computed(() => {
  return baseSaleAttrList.value.filter((item) =>
    spuSaleAttrList.value.every((item1) => item1.saleAttrName !== item.name)
  );
});

// 收集下拉属性值
const saleAttrIdName = ref();

// 添加销售属性
const addSaleAttr = () => {
  const [baseSaleAttrId, saleAttrName] = saleAttrIdName.value.split(":");

  spuSaleAttrList.value.push({
    baseSaleAttrId,
    saleAttrName,
    spuSaleAttrValueList: [], //应该是空数组
  });
};

// 小标签逻辑
const InputRef = ref<InstanceType<typeof ElInput>>();

const showInput = (row: SpuSaleAttrData) => {
  row.isEdit = true;
  nextTick(() => {
    InputRef.value!.input!.focus();
  });
};

const handleInputConfirm = (row: SpuSaleAttrData) => {
  let { baseSaleAttrId, saleAttrValueName } = row;

  if (!saleAttrValueName || !saleAttrValueName.trim()) {
    ElMessage.error("请输入合法数据！");
    row.saleAttrValueName = "";
    row.isEdit = false;
    return;
  }
  let isRepeat = spuSaleAttrList.value.every(
    (item) => item.saleAttrName !== row.saleAttrName
  );
  // 有相等的情况下
  if (isRepeat) {
    ElMessage.error("属性值不能相等！");
    row.saleAttrValueName = "";
    row.isEdit = false;
    return;
  }
  console.log(row);

  row.spuSaleAttrValueList.push({ baseSaleAttrId, saleAttrValueName });
  row.saleAttrValueName = "";
  row.isEdit = false;
};

// 照片墙逻辑

const dialogImageUrl = ref("");
const dialogVisible = ref(false);
// 删除图片对应回调
const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  spuImageList.value = uploadFiles as any;
};
// 预览大图
const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!;
  dialogVisible.value = true;
};
// 添加图片成功回调
const handleSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile,
  uploadFiles
) => {
  console.log(response, uploadFiles);

  spuSaleAttrList.value = uploadFiles as any;
};

// 保存操作
const categoryStore = useCategoryStore();
const save = async () => {
  // 整理参数
  let spu = spuForm.value;
  spu.category3Id = categoryStore.category3Id;
  spu.spuImageList = spuImageList.value.map((item) => {
    return {
      imgName: item.name as string,
      imgUrl: item.imgUrl || (item.response as ResponseData).data,
    };
  });
  // 清除自己添加的销售属性列表
  spuSaleAttrList.value.forEach((item) => {
    delete item.isEdit;
    delete item.saleAttrValueName;
  });
  spu.spuSaleAttrList = spuSaleAttrList.value;

  try {
    await spuApi.addOrUpdate(spu);
    ElMessage.success("保存spu成功");
    emits("changeState", 1);
  } catch (error) {
    ElMessage.error("保存spu失败");
  }
};
</script>

<style lang="less" scoped></style>
